/*
 * Copyright (C) 2013 Andreas Stuetz <andreas.stuetz@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.elinkway.infinitemovies.ui.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue.IdleHandler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.MenuItemCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mobad.feeds.NativeResponse;
import com.elinkway.infinitemovies.adaction.CommonAdActionHandle;
import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.MoviesHttpAsyncTask;
import com.elinkway.infinitemovies.async.RequestAppConfigTask;
import com.elinkway.infinitemovies.async.RequestResultListener;
import com.elinkway.infinitemovies.bean.AlbumUpdateInfoBean;
import com.elinkway.infinitemovies.bean.AlbumUpdateInfoList;
import com.elinkway.infinitemovies.bean.AppConfig;
import com.elinkway.infinitemovies.bean.CommonBean;
import com.elinkway.infinitemovies.bean.Favorite;
import com.elinkway.infinitemovies.bean.HotAppConfig;
import com.elinkway.infinitemovies.bean.HzPayload;
import com.elinkway.infinitemovies.bean.JumpData;
import com.elinkway.infinitemovies.bean.NewAdDataBean;
import com.elinkway.infinitemovies.bean.Payload;
import com.elinkway.infinitemovies.bean.PlayRecord;
import com.elinkway.infinitemovies.bean.SDKPayload;
import com.elinkway.infinitemovies.bean.ServerPayload;
import com.elinkway.infinitemovies.bean.TtPayload;
import com.elinkway.infinitemovies.bean.UploadCollectionBean;
import com.elinkway.infinitemovies.bean.XfPayload;
import com.elinkway.infinitemovies.bean.YzPayload;
import com.elinkway.infinitemovies.bigdata.BigDataApi;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.bigdata.BigDataLaunchQuitActionTask;
import com.elinkway.infinitemovies.bigdata.BigDataStats;
import com.elinkway.infinitemovies.bigdata.BigDataUtils;
import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.dao.FavoriteDao;
import com.elinkway.infinitemovies.dao.PlayRecordDao;
import com.elinkway.infinitemovies.dao.PreferencesManager;
import com.elinkway.infinitemovies.download.Constants;
import com.elinkway.infinitemovies.download.DownloadHelper;
import com.elinkway.infinitemovies.download.DownloadJob;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.http.parser.AlbumUpdateInfoListParser;
import com.elinkway.infinitemovies.http.parser.CommonParser;
import com.elinkway.infinitemovies.http.requestInterface.RequestCommonInterface;
import com.elinkway.infinitemovies.http.requesttask.RequestAdTask;
import com.elinkway.infinitemovies.http.requesttask.RequestAlbumInfoTask;
import com.elinkway.infinitemovies.http.requesttask.RequestDoPlayRecordTask;
import com.elinkway.infinitemovies.http.requesttask.RequestUserPlayRecordsTask;
import com.elinkway.infinitemovies.listener.MyOnAdListener;
import com.elinkway.infinitemovies.listener.MyTencentLocationListener;
import com.elinkway.infinitemovies.push.PushBroadcastReceiver;
import com.elinkway.infinitemovies.push.PushStatsPoster;
import com.elinkway.infinitemovies.selfdata.AdRequestStatis;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.SelfDataConstant;
import com.elinkway.infinitemovies.selfdata.UploadUtil;
import com.elinkway.infinitemovies.selfdata.bean.LaunchDurationDataRecord;
import com.elinkway.infinitemovies.selfdata.bean.MyDataRecord;
import com.elinkway.infinitemovies.selfdata.bean.YiDianGuideDataRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.service.UpdateService;
import com.elinkway.infinitemovies.ui.activity.commonwebview.CommonWebViewActivity;
import com.elinkway.infinitemovies.ui.activity.play.PlayerUtils;
import com.elinkway.infinitemovies.ui.fragment.ChannelFragment;
import com.elinkway.infinitemovies.ui.fragment.HomeTestFragment;
import com.elinkway.infinitemovies.ui.fragment.MyFragment;
import com.elinkway.infinitemovies.ui.fragment.NewHomeFragment;
import com.elinkway.infinitemovies.ui.fragment.OnePointFragment;
import com.elinkway.infinitemovies.ui.fragment.RankFragment;
import com.elinkway.infinitemovies.ui.fragment.TopicFragment;
import com.elinkway.infinitemovies.ui.fragment.UtilsFragment;
import com.elinkway.infinitemovies.utils.AdStatisticsSp;
import com.elinkway.infinitemovies.utils.AppListUtil;
import com.elinkway.infinitemovies.utils.CDEManager;
import com.elinkway.infinitemovies.utils.DeepLinkUtil;
import com.elinkway.infinitemovies.utils.DialogUtil;
import com.elinkway.infinitemovies.utils.IdUtils;
import com.elinkway.infinitemovies.utils.LiteAppManager;
import com.elinkway.infinitemovies.utils.LogCat;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.MoviesConstant;
import com.elinkway.infinitemovies.utils.MoviesUtils;
import com.elinkway.infinitemovies.utils.MyLocationManager;
import com.elinkway.infinitemovies.utils.NetWorkTypeUtils;
import com.elinkway.infinitemovies.utils.PushUtil;
import com.elinkway.infinitemovies.utils.ReportUtil;
import com.elinkway.infinitemovies.utils.SharePreferenceManager;
import com.elinkway.infinitemovies.utils.StringUtil;
import com.elinkway.infinitemovies.utils.ToastUtil;
import com.elinkway.infinitemovies.utils.UIs;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.utils.UpdateManager;
import com.elinkway.infinitemovies.utils.UpdateManager.UpdateListener;
import com.elinkway.infinitemovies.utils.UpdateSnifferManager;
import com.elinkway.infinitemovies.utils.Utils;
import com.elinkway.infinitemovies.view.BaiduInterAdView;
import com.elinkway.infinitemovies.view.CustomDialog;
import com.elinkway.infinitemovies.view.GdtNativeAdView;
import com.elinkway.infinitemovies.view.HzPayAdView;
import com.elinkway.infinitemovies.view.ScorePopupWindow;
import com.elinkway.infinitemovies.view.TtPayAdView;
import com.elinkway.infinitemovies.view.XfPayAdView;
import com.elinkway.infinitemovies.view.YzPayAdView;
import com.handmark.pulltorefresh.library.HeaderView;
import com.le123.ysdq.R;
import com.lvideo.http.bean.LVideoDataHull;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.qq.e.ads.nativ.NativeADDataRef;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPluginPlatformInterface;
import cn.jpush.android.api.JPushInterface;

public class NewMainActivity extends BaseActionBarActivity implements RequestCommonInterface, HeaderView {

    public static final String TAG = "NewMainActivity";
    public static final int YIDIAN_OPEN_NUM_10 = 10;
    public static final int YIDIAN_OPEN_NUM_2 = 2;

    private String CONFIG_NAME = "appconfig";

    private String CLICK_TIME = "click_time";

    private String INSITE = "insite";

    private String OUTSITE_360 = "outsite_360";

    private String HIDE_APP_STORE = "0";

    private String SHOW_NORMAL_APPSTORE = "1";

    private String SHOW_RED_CORNER = "2";

    private HotAppConfig mHotAppConfig;

    private FavoriteDao favoriteDao;
    private List<Favorite> favoriteList;
    private List<UploadCollectionBean> uploadCollectionList;
    private RequestAlbumUpdateInfoListTask requstAlbumUpdateInfoListTask;
    public AlbumUpdateInfoList albumUpdateInfoList;
    public boolean update;

    private PlayRecordDao mPlayRecordDao;
    private List<PlayRecord> mPlayRecordList;

    private int backCount = 0;

    // 网络变化广播接收
    private NetworkCheckReceiver mCheckReceiver;

    /**
     * 评分弹窗
     */
    private ScorePopupWindow mScorePopupWindow;
    private RelativeLayout mMain_parent;
    /**
     * 创建快捷方式
     */
    private static final String ACTION_INSTALL_SHORTCUT = "com.android.launcher.action.INSTALL_SHORTCUT";
    /**
     * 升级
     */
    private UpdateManager mUpdateManager;

    /**
     * 收藏播放记录合并
     */
    private CustomDialog mLocalDataSyncDialg;
    private CustomDialog.Builder mLocalDataSyncBuilder;

    /**
     * 请求应用程序配置的Task
     */
    private RequestAppConfigTask mAppConfigTask;

    private Context mContext;

    private MyOnClickListener mOnClickListener;

    private Menu menu;

    private MyLocationManager mLocationManager;

    private boolean mHasCheckedLiteApp = false;

    private RequestAddAllFavoriteTask mRequestAddAllFavoriteTask;
//    private RequestGetFavoriteListTask mRequestGetFavoriteListTask;

    private SharedPreferences mLoginSp;

    private Handler mHandler;

    private Dialog mExitDialog;

    private View mExitView;

    private RelativeLayout mExitAdRelativeLayout;

//    private ImageView mExitAdHeadImage;

    private TextView mExitHeadText;

    private ImageView mExitImage;

    private BaiduInterAdView baiduInterExitAdView;
    private TextView mExitTipTv;
    private ImageView mExitLogoIv;

    private RelativeLayout.LayoutParams reLayoutParams;

    private RelativeLayout mInterAdRelativeLayout;

    private NativeResponse mNativeResponse;

    private int mCurrentTabPosition;

    private LinearLayout tabHomeLl;
    private LinearLayout tabHotLl;
    private LinearLayout tabChannelLl;
    private LinearLayout tabTopicLl;
    private LinearLayout tabRankLl;
    private LinearLayout tabMyLl;
    FragmentManager fManager;
    private NewHomeFragment homeFragment;
    private Fragment hotFragment;
    private Fragment utilsFragment;
    private Fragment topicFragment;
    private Fragment rankFragment;
    private Fragment myFragment;
    /**
     * 针对快看显示广告位
     */
    private FrameLayout adContainer;
    private ImageView adIcon;
    private ImageView adTip;

    private boolean isShowDownloadRed;
    private boolean isSecondStatus;
    private boolean isShowWhiteBg;
    private int titleAlpha = 255;
    private boolean isFirstCreate = true;

    private String mCurrentBottomTab = "home";
    private JPluginPlatformInterface pHuaweiPushInterface;
    private NewAdDataBean quitAdData;
    private LaunchDurationDataRecord launchDuration; // 启动时长日志
    private MyDataRecord mTabDataRecord; // 底部五个tab点击日志
    private Bundle mBundle;
    private Timer mReportTimer;
    private List<NativeADDataRef> mExitGdtAdList;
    private Timer mExitGdtAdTimer;
    /**
     * 一点资讯引导页
     */
    private View yidianGuide; // 引导页面
    private LinearLayout lyYidianHot; // 热门tab图标
    private ImageView ImgYidianDesc; // 热门提示文字
    private int openNum = 1; // 一点资讯标签下启动次数
    private String bottomIndex;

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle, if it returns
        // true, then it has handled the app icon touch event
        switch (item.getItemId()) {
            case R.id.action_appstore:
                if (null != mHotAppConfig) {
                    if (!TextUtils.isEmpty(mHotAppConfig.getDisplay())
                            && SHOW_RED_CORNER.equals(mHotAppConfig.getDisplay())) {
                        SharedPreferences appConfigPreferences = getSharedPreferences(
                                CONFIG_NAME, Context.MODE_PRIVATE);
                        String currTime = Utils.getTodayTime();
                        Editor eidtor = appConfigPreferences.edit();
                        eidtor.putString(CLICK_TIME, currTime);
                        eidtor.commit();
                    }
                    showAppStoreIconRed(false);
                    String source = mHotAppConfig.getSource();
                    showStoreBySource(source);
                }
                break;
            case R.id.menu_download:
                Intent intent = new Intent(NewMainActivity.this,
                        DownloadActivity.class);
                startActivity(intent);
                break;
            case R.id.action_history:
                PlayHistoryActivity.launch(NewMainActivity.this);
                UmengEventPoster.postPageVisitTime(UmengEventPoster.VISIT_HISTORY, MoviesApplication
                .getInstance().getLastPageClassName());
                break;
            case R.id.action_search:
                SearchActivity.launch(NewMainActivity.this);
                UmengEventPoster.postPageVisitTime(UmengEventPoster.VISIT_SEARCH, MoviesApplication
                        .getInstance().getLastPageClassName());
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void showStoreBySource(String source) {
        if (INSITE.equals(source)) {
            String webUrl = mHotAppConfig.getUrl();
            if (!TextUtils.isEmpty(webUrl)) {
                JumpData jumpData = new JumpData();
                jumpData.setPlayUrl(webUrl);
                jumpData.setName(getString(R.string.hotappsuggest));
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                intent.putExtra(Utils.FROM, Utils.FROM_APP);
                intent.setClass(mContext, CommonWebViewActivity.class);
                bundle.putSerializable(Utils.CHANNEL_DTAT, jumpData);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        } else if (OUTSITE_360.equals(source)) {
            // 展现360广告墙
            //QihooAdAgent.loadAd(mContext);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        super.onCreate(savedInstanceState);
        super.setActionBarActivityClassName(TAG);
        Intent intent = getIntent();
        if (intent != null) {
            mBundle = intent.getExtras();
        }
        // 埋点
        staticOnCreate();
        if (mTabDataRecord == null) {
            mTabDataRecord = MyDataRecordCreater.build(MyDataRecord.class);
        }
        LogUtils.e("JPush", "JPush register id " + JPushInterface.getRegistrationID(this));
        pHuaweiPushInterface = new JPluginPlatformInterface(this.getApplicationContext());
        setContentView(R.layout.activity_new_main);
        MoviesApplication.getInstance().setIsRunning(true);
        mContext = this;
        fManager = getSupportFragmentManager();
        List<Fragment> fragments = fManager.getFragments();
        if (fragments != null) {
            FragmentTransaction ft = fManager.beginTransaction();
            for (Fragment f : fragments) {
                if(f != null){
                    ft.remove(f);
                }
            }
            ft.commitAllowingStateLoss();
        }

        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch(msg.what) {
                    case MoviesConstant.NEED_REPORT_DATA:
                        new UploadUtil().upload();
                        break;
                    case MoviesConstant.NEED_REQUEST_GDTAD:
                        GdtNativeAdView gdtAd = new GdtNativeAdView(NewMainActivity.this, "exit", null, "exit");
                        gdtAd.setAdListener(new MyOnAdListener() {
                            @Override
                            public void onAdDismissed() {

                            }

                            @Override
                            public void onAdFailed() {

                            }

                            @Override
                            public void onAdPresent() {

                            }

                            @Override
                            public void onAdSuccess(Object obj) {
                                mExitGdtAdList = (List<NativeADDataRef>) obj;
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        for (NativeADDataRef adItem:mExitGdtAdList){
                                            ImageLoader.getInstance().loadImageSync(adItem.getImgUrl());
                                        }
                                    }
                                }).start();
                            }
                        });
                        gdtAd.loadAD(IdUtils.EXIT_GDTAD_ID);
                        break;
                }
                super.handleMessage(msg);
            }
        };
        Long startTime = System.currentTimeMillis();
        // TODO
        showAdActivity();
        mLocationManager = new MyLocationManager(this, new MyNewLocationListener());
        BigDataStats.postEnv();
        BigDataLaunchQuitActionTask launchStatsTask = new BigDataLaunchQuitActionTask();
        launchStatsTask.setAcode(BigDataConstants.ACODE_LAUNCH)
                .setApType(BigDataConstants.AP_LAUNCH_USER)
                .setNT(BigDataUtils.getNetType(this)).onEventStart();
        Bundle bundle = getIntent().getExtras();
        final String FROM_PUSH_KEY = "from_push_notification";
        if (null != bundle && bundle.containsKey(FROM_PUSH_KEY)
                && bundle.getBoolean(FROM_PUSH_KEY)) {
            launchStatsTask.setApType(BigDataConstants.AP_LAUNCH_PUSH);
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(getIntent() != null){
                    if(!IdUtils.SCHEME_NAME.equalsIgnoreCase(getIntent().getScheme())){
                        jumpFromH5(getIntent());
                    }
                }
            }
        }, 2000);
        Uri uri = getIntent().getData();
        if (uri != null && "album".equals(uri.getQueryParameter("action"))) {
            launchStatsTask.setApType(BigDataConstants.AP_LAUNCH_SHARE);
        }
        invokeByBrowser(uri);

        // SDK初始化-必须 奇虎换量的初始化
        //QihooAdAgent.init(mContext);
        isOriginal();
        mOnClickListener = new MyOnClickListener();
        initBottomView();
        initActionBar();
        initControl();
        saveQrCode();
        MoviesApplication.getInstance().setActivityStack(this);
        // startPushBroadcastReceiver();
        PushStatsPoster.postPushClickStats(getIntent().getExtras(),
                UmengEventPoster.PUSH_TYPE_OTHER);

        if (null != mScorePopupWindow) {
            mScorePopupWindow.showPopView();
        }
        DownloadHelper.restoreUserDownloadPath();
        DownloadHelper.initSdcardCount();

        // 快捷方式
        boolean firstLaunch = PreferencesManager.getInstance().isFirstLaunch();
        if (firstLaunch) {
            installShortCut();
        }
        UpdateSnifferManager.getInstance().startUpdate();

        actionAppStoreState(false);
        /**
         * 请求APP的配置
         */
        //requestAppConfig();
        //initQihooConfig();
        launchStatsTask.onEventStop(false);
        launchStatsTask.setAR(BigDataConstants.AR_SUCCESS);
        BigDataStats.post(launchStatsTask);
        // Intent i = new Intent(this, LiveActivity.class);
        // startActivity(i);
        LogUtils.userTime("onCreate", startTime); // TAG useTime
        LogUtils.e(TAG, "!!!!端口号!!!!!!!!"
                + CDEManager.getInstance(this).getmCdeHelper().getServicePort());
        LogUtils.e(TAG, "!!!!端口号!!!!!!!!"
                + CDEManager.getInstance(this).getmCdeHelper().getServicePort());
        checkLiteApp(); // 启动测liteApp安装与否
        initDialg();

        mLoginSp = getSharedPreferences(SettingManage.LOGIN_INFO, Context.MODE_PRIVATE);
        if(!TextUtils.isEmpty(mLoginSp.getString(LoginActivity.TOKEN, ""))){
            //已登录的操作
            new RequestUserPlayRecordsTask(this, 0, 200).start();
        }else{
            //未登录的操作
            favoriteDao = new FavoriteDao(this);
            List<String> noPosterFavoriteList = favoriteDao.getNoPosterAidList();
            if(noPosterFavoriteList != null && noPosterFavoriteList.size() > 0){
                new RequestAlbumInfoTask(this, noPosterFavoriteList, "favorite").start();
            }

            mPlayRecordDao = new PlayRecordDao(this);
            List<String> noPosterRecordList = mPlayRecordDao.getNoPosterAidList();
            if(noPosterRecordList != null && noPosterRecordList.size() > 0){
                new RequestAlbumInfoTask(this, noPosterRecordList, "record").start();
            }
        }
        init(false);
        AppListUtil.uploadAppList();

        mReportTimer = new Timer();
        mReportTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(MoviesConstant.NEED_REPORT_DATA);
            }
        },0, 180000);

        mExitGdtAdTimer = new Timer();
        mExitGdtAdTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(MoviesConstant.NEED_REQUEST_GDTAD);
            }
        }, 20000, 1800000);
    }

    private void staticOnCreate() {
        if (mBundle == null) {
            return;
        }
        launchDuration = (LaunchDurationDataRecord)mBundle.getSerializable(SplashActivity.LAUNCHLOG);
        if (launchDuration != null) {
            launchDuration.setHomeOncreate(System.currentTimeMillis() + "");
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        pHuaweiPushInterface.onStart(this);
    }

    private void parseScheme(Uri uriString) {
        Intent jumpIntent = new Intent();
        jumpIntent.putExtra(DeepLinkUtil.ACTION_TYPE, uriString.getQueryParameter(DeepLinkUtil.ACTION_TYPE));
        jumpIntent.putExtra(DeepLinkUtil.VIDEO_ID, uriString.getQueryParameter(DeepLinkUtil.VIDEO_ID));
        jumpIntent.putExtra(DeepLinkUtil.VIDEO_TYPE, uriString.getQueryParameter(DeepLinkUtil.VIDEO_TYPE));
        jumpIntent.putExtra(DeepLinkUtil.NAME, uriString.getQueryParameter(DeepLinkUtil.NAME));
        jumpIntent.putExtra(DeepLinkUtil.THEME_ID, uriString.getQueryParameter(DeepLinkUtil.THEME_ID));
        jumpIntent.putExtra(DeepLinkUtil.SITE, uriString.getQueryParameter(DeepLinkUtil.SITE));
        jumpIntent.putExtra(DeepLinkUtil.EPISODE_NUMBER, uriString.getQueryParameter(DeepLinkUtil.EPISODE_NUMBER));
        jumpIntent.putExtra(DeepLinkUtil.URL, uriString.getQueryParameter(DeepLinkUtil.URL));
        jumpIntent.putExtra(DeepLinkUtil.TITLE, uriString.getQueryParameter(DeepLinkUtil.TITLE));
        jumpIntent.putExtra(DeepLinkUtil.SOURCE, uriString.getQueryParameter(DeepLinkUtil.SOURCE));
        jumpFromH5(jumpIntent);
    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    private void initBottomView() {
        // 底部tab
        tabHomeLl = (LinearLayout) findViewById(R.id.tab_home_ll);
        tabHotLl = (LinearLayout) findViewById(R.id.tab_hot_ll);
        tabChannelLl = (LinearLayout) findViewById(R.id.tab_channel_ll);
        tabTopicLl = (LinearLayout) findViewById(R.id.tab_topic_ll);
        tabRankLl = (LinearLayout) findViewById(R.id.tab_rank_ll);
        tabMyLl = (LinearLayout) findViewById(R.id.tab_my_ll);
        tabHomeLl.setOnClickListener(mOnClickListener);
        tabHotLl.setOnClickListener(mOnClickListener);
        tabChannelLl.setOnClickListener(mOnClickListener);
        tabTopicLl.setOnClickListener(mOnClickListener);
        tabRankLl.setOnClickListener(mOnClickListener);
        tabMyLl.setOnClickListener(mOnClickListener);
        tabChannelLl.setVisibility(MoviesUtils.isProductCjsp()?View.GONE:View.VISIBLE);
        // 引导页
        yidianGuide = findViewById(R.id.ly_yidian_guide);
        lyYidianHot = (LinearLayout)yidianGuide.findViewById(R.id.yidian_guide_hot); // 热门tab图标
        ImgYidianDesc = (ImageView)yidianGuide.findViewById(R.id.yidian_guide_desc); // 热门提示文字
        yidianGuide.setOnClickListener(mOnClickListener);
        lyYidianHot.setOnClickListener(mOnClickListener);
        ImgYidianDesc.setOnClickListener(mOnClickListener);

        if(false){
            String hotText = SharePreferenceManager.getVaule(this, SharePreferenceManager.YIDIAN_TAG, "");
            if(Constants.TAG_YIDIAN.equals(hotText)){
                // 一点咨询底部tab
                tabHotLl.setVisibility(View.VISIBLE);
                tabChannelLl.setVisibility(View.GONE);
                tabRankLl.setVisibility(View.GONE);
                // 一点咨询引导页
                openNum = SharePreferenceManager.getVaule(this, SharePreferenceManager.YIDIAN_OPEN_NUM,1);
                int num = openNum;
                if (num == YIDIAN_OPEN_NUM_2 || num == YIDIAN_OPEN_NUM_10) {
                    yidianGuide.setVisibility(View.VISIBLE);
                } else {
                    yidianGuide.setVisibility(View.GONE);
                }
                if (num <= YIDIAN_OPEN_NUM_10) {
                    num++;
                    SharePreferenceManager.saveVaule(this, SharePreferenceManager.YIDIAN_OPEN_NUM,num);
                }
            }
        }
    }

    /**
     * 检测liteApp安装与否
     */
    private void checkLiteApp() {
        LogUtils.e(UpdateService.TAG, "#######################checkLiteApp called#######################");
        if (!mHasCheckedLiteApp) {
            LogUtils.e(UpdateService.TAG, "检测Lite App安装状态");
            LiteAppManager.getInstance().checkInstallState(mContext);
            mHasCheckedLiteApp = true;
        } else
            LogUtils.e(UpdateService.TAG, "已经安装或者下载liteApp");
    }

    /**
     * 显示广告
     */
    private void showAdActivity() {
        if (mBundle == null) {
            return;
        }
        if (mBundle.getBoolean(SplashActivity.ISADCLICK, false)) {
            ServerPayload serverPayload = (ServerPayload) mBundle.getSerializable(Utils.AD_INFO);
            if (serverPayload != null && !TextUtils.isEmpty(serverPayload.lp)) {
                CommonAdActionHandle.getInstance().doServerAd(this, serverPayload, MoviesHttpApi.LAUNCH);
            }
        }
    }

    /**
     * 地域策略执行后，才开始请求其他接口
     * 地域策略超时3秒钟，3秒之内完成地域策略，保存经纬度，则执行该方法，并且之后所有请求接口都附加地域策略参数经纬度
     * 如果超时3秒，也执行该方法，所有接口地域策略参数为空
     */
    private void init(boolean isLocation) {
        if (!isLocation) {
            setBottomSelete(1);
        }
        startPushBroadcastReceiver();
    }

    private void initDialg() {
        mLocalDataSyncBuilder = new CustomDialog.Builder(this);
        mLocalDataSyncBuilder.setMessage(getResources().getString(R.string.has_sync_data));
        mLocalDataSyncBuilder.setPositiveButton(R.string.sync, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                ToastUtil.showShortToast(NewMainActivity.this, getResources().getString(R.string.syncing));
                //将本地收藏数据和播放记录数据上传TODO
                uploadCollectionList = new ArrayList<UploadCollectionBean>();
                for(int i = 0; i < favoriteList.size(); i++) {
                    UploadCollectionBean uploadCollectionBean = new UploadCollectionBean();
                    uploadCollectionBean.setAction("0");
                    uploadCollectionBean.setRelatedId(favoriteList.get(i).getAid());
                    uploadCollectionBean.setTime(favoriteList.get(i).getFavoriteTime() + "");
                    uploadCollectionBean.setType("1");
                    uploadCollectionList.add(uploadCollectionBean);
                }
                mRequestAddAllFavoriteTask = new RequestAddAllFavoriteTask(getApplicationContext(), uploadCollectionList);
                mRequestAddAllFavoriteTask.start();

                if(mPlayRecordList != null && mPlayRecordList.size() > 0){
                    List<PlayRecord> uploadList = new ArrayList<PlayRecord>();
                    for (int i = 0;i < mPlayRecordList.size(); i++){
                        if(mPlayRecordList.get(i) != null && !TextUtils.isEmpty(mPlayRecordList.get(i).getVid())){
                            uploadList.add(mPlayRecordList.get(i));
                        }
                    }
                    if(uploadList.size() > 0){
                        new RequestDoPlayRecordTask(NewMainActivity.this, mPlayRecordList, "merge").start();
                    }
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (myFragment != null) {
                            ((MyFragment)myFragment).updateFavoriteRecord();
                            ((MyFragment)myFragment).updateHistoryRecord();
                            ((MyFragment)myFragment).updateDownloadRecord();
                        }
                    }
                }, 300);
                dialog.dismiss();
            }
        });
        mLocalDataSyncBuilder.setNegativeButton(R.string.no_sync, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        mLocalDataSyncDialg = mLocalDataSyncBuilder.create();
    }

    @Override
    public void requestSuccess(int updateId, Object data, String name) {
        if(MoviesHttpApi.ADD_FAVORITE.equals(name)) {
            ToastUtil.showShortToast(NewMainActivity.this, getResources().getString(R.string.sync_success));
            for(int i = 0; i < favoriteList.size(); i++) {
                favoriteDao.delete(favoriteList.get(i).getAid());
            }
            if(uploadCollectionList != null) {
                uploadCollectionList.clear();
            }
        }
    }

    @Override
    public void requestFail(String name) {
        if(MoviesHttpApi.ADD_FAVORITE.equals(name)) {
            ToastUtil.showShortToast(NewMainActivity.this, getResources().getString(R.string.sync_fail));
        }
    }

    @Override
    public void netError(String name) {
        if(MoviesHttpApi.ADD_FAVORITE.equals(name)) {
            ToastUtil.showShortToast(NewMainActivity.this, this.getResources().getString(R.string.sync_fail));
        }

    }

    public class MyNewLocationListener implements MyTencentLocationListener {

        @Override
        public void onLocationSuccese(String cityInfo) {
            init(true);
            LogUtils.e(MyLocationManager.TAG, "成功:城市信息：" + cityInfo);
        }

        @Override
        public void onLocationTimeOut() {
            init(true);
            LogUtils.e(MyLocationManager.TAG, "超时");
        }
    }

    private void invokeByBrowser(Uri uri) {
        // 通过ysdq://launch?action={album}&aid={2_267715}[&name={name}] 跳转
        if (uri == null) {
            return;
        }
        try {
            if ("album".equals(uri.getQueryParameter("action"))) {
                String aid = uri.getQueryParameter("aid");
                String title = uri.getQueryParameter("name");
                VideoDetailActivity.launch(this, aid, "", title, "", "", "", "0","","");
            } else if (IdUtils.SCHEME_NAME.equalsIgnoreCase(uri.getScheme())){
                parseScheme(uri);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void jumpFromH5(Intent intent) {
        DeepLinkUtil.uploadDeepLink(intent);
        if (TextUtils.isEmpty(intent.getStringExtra(DeepLinkUtil.ACTION_TYPE))) {
            return;
        }
        String actionType = intent.getStringExtra(DeepLinkUtil.ACTION_TYPE);
        String source = intent.getStringExtra(DeepLinkUtil.SOURCE);
        if (DeepLinkUtil.ActionType.TOPIC_DETAIL.equals(actionType)) {
            String themeId = intent.getStringExtra(DeepLinkUtil.THEME_ID);
            String name = intent.getStringExtra(DeepLinkUtil.NAME);
            TopicDetailActivity.launch(NewMainActivity.this, themeId, name);
        } else if (DeepLinkUtil.ActionType.OLD_VIDEO_DETAIL_NO_PLAY.equals(actionType)) {
            String videoId = intent.getStringExtra(DeepLinkUtil.VIDEO_ID);
            String videoType = intent.getStringExtra(DeepLinkUtil.VIDEO_TYPE);
            String site = intent.getStringExtra(DeepLinkUtil.SITE);
            String episodeNumber = intent.getStringExtra(DeepLinkUtil.EPISODE_NUMBER);
            String name = intent.getStringExtra(DeepLinkUtil.NAME);
            String themeId = intent.getStringExtra(DeepLinkUtil.THEME_ID);
            VideoDetailActivity.launch(NewMainActivity.this, videoId, videoType, name, "", themeId, "", episodeNumber, "" , "");
        } else if (DeepLinkUtil.ActionType.RANK.equals(actionType)) {
            String videoType = intent.getStringExtra(DeepLinkUtil.VIDEO_TYPE);
            RankDetailActivity.launch(NewMainActivity.this, videoType);
        } else if (DeepLinkUtil.ActionType.VIDEO_PLAY.equals(actionType)) {
            String videoId = intent.getStringExtra(DeepLinkUtil.VIDEO_ID);
            String videoType = intent.getStringExtra(DeepLinkUtil.VIDEO_TYPE);
            String site = intent.getStringExtra(DeepLinkUtil.SITE);
            String episodeNumber = intent.getStringExtra(DeepLinkUtil.EPISODE_NUMBER);
            String name = intent.getStringExtra(DeepLinkUtil.NAME);
            String themeId = intent.getStringExtra(DeepLinkUtil.THEME_ID);
            VideoDetailActivity.launch(NewMainActivity.this, videoId, videoType, name, "", themeId, "", episodeNumber, "" , "");
        } else if (DeepLinkUtil.ActionType.H5.equals(actionType)) {
            String url = intent.getStringExtra(DeepLinkUtil.URL);
            String title = intent.getStringExtra(DeepLinkUtil.TITLE);
            Utils.jumpWebViewActivity(NewMainActivity.this, url, title);
        } else if (DeepLinkUtil.ActionType.TOPIC.equals(actionType)) {
            setBottomSelete(3);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        LogCat.e(TAG, "onNewItent");
        handleBottomSelect();
        try {
            Uri uri = intent.getData();
            invokeByBrowser(uri);
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onNewIntent(intent);
    }

    /**
     * 创建桌面图标
     */
    private void installShortCut() {
        Intent shortcutIntent = new Intent();
        // 设置点击快捷方式时启动的Activity,因为是从Lanucher中启动，所以包名类名要写全。
        shortcutIntent.setComponent(new ComponentName(getPackageName(),
                SplashActivity.class.getName()));
        // 设置启动的模式
        shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
                | Intent.FLAG_ACTIVITY_NEW_TASK);
        shortcutIntent.setAction("android.intent.action.MAIN");
        shortcutIntent.addCategory("android.intent.category.LAUNCHER");
        Intent resultIntent = new Intent(ACTION_INSTALL_SHORTCUT);
        // 设置快捷方式图标
        resultIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                Intent.ShortcutIconResource.fromContext(this,
                        R.drawable.ic_launcher));
        // 启动的Intent
        resultIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        // 设置快捷方式的名称
        resultIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
                getString(R.string.app_name));
        resultIntent.putExtra("duplicate", false);
        sendBroadcast(resultIntent);
    }

    /**
     * 执行App配置请求 zhangshuo 2014年10月13日 下午4:53:07
     */
    private void requestAppConfig() {
        if (null != mAppConfigTask && !mAppConfigTask.isCancelled()) {
            mAppConfigTask.cancel();
        }
        mAppConfigTask = new RequestAppConfigTask(this);
        mAppConfigTask.setmListener(new AppConfigRequestListener());
        mAppConfigTask.start();
    }

    public class AppConfigRequestListener implements
            RequestResultListener<AppConfig> {

        @Override
        public boolean onRequestFailed() {
            // 请求数据失败隐藏应用市场icon
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, AppConfig result) {
            ShowAppStoreLogic(result);
        }

        @Override
        public void onPreRequest() {

        }

    }

    private void ShowAppStoreLogic(AppConfig result) {
        if (null != result) {
            HotAppConfig hotAppConfig = result.getHotAppConfig();
            if (null != hotAppConfig) {
                mHotAppConfig = hotAppConfig;
                // 获取应用市场展现状态
                String disPlay = hotAppConfig.getDisplay();
                appStoreState(disPlay);
            }
        }
    }

    private void showAppStoreIconRed(final boolean flag) {
        actionAppStoreState(true);
        Looper.myQueue().addIdleHandler(new IdleHandler() {
            @Override
            public boolean queueIdle() {
                try {
                    if (null != menu) {
                        final MenuItem appStoreitem = menu
                                .findItem(R.id.action_appstore);
                        ImageView appStoreIg = (ImageView) (MenuItemCompat
                                .getActionView(appStoreitem)
                                .findViewById(R.id.action_icon));
                        if (flag) {
                            appStoreIg
                                    .setImageResource(R.drawable.button_title_appstore_red_selector);
                        } else {
                            appStoreIg
                                    .setImageResource(R.drawable.button_title_appstore_selector);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }
        });
    }

    private void actionAppStoreState(final boolean flag) {
        Looper.myQueue().addIdleHandler(new IdleHandler() {
            @Override
            public boolean queueIdle() {
                try {
                    if (null != menu) {
                        menu.findItem(R.id.action_appstore).setVisible(flag);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }
        });
    }

    private void appStoreState(String disPlay) {
        if (HIDE_APP_STORE.equals(disPlay)) {
            actionAppStoreState(false);
        } else if (SHOW_NORMAL_APPSTORE.equals(disPlay)) {
            showAppStoreIconRed(false);
        } else if (SHOW_RED_CORNER.equals(disPlay)) {
            SharedPreferences appConfigPreferences = getSharedPreferences(
                    CONFIG_NAME, Context.MODE_PRIVATE);
            String updateTime = appConfigPreferences.getString(CLICK_TIME, "");
            String currTime = Utils.getTodayTime();
            // 如果之前已经展示了则不展示红点
            if (currTime.equals(updateTime)) {
                showAppStoreIconRed(false);
            } else {
                showAppStoreIconRed(true);
            }
        } else {

        }
    }

    /**
     * 存储二维码至本地 zhangshuo 2014年6月4日 下午9:58:28
     */
    private void saveQrCode() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                Bitmap thumb = Utils.getRes(NewMainActivity.this,
                        Utils.SHARE_QRCODE);
                Utils.saveFile(thumb, Utils.SHARE_QRCODE);
            }
        }.start();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        try {   //避免umeng的一个崩溃
            super.onSaveInstanceState(outState);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void initActionBar() {
        super.initActionBar();
        mLeftBackIv.setVisibility(View.GONE);
        mRightFirstTv.setVisibility(View.GONE);
        mRightFirstIv.setVisibility(View.VISIBLE);
        mRightSecondIv.setVisibility(View.VISIBLE);
        mRightSecondIv.setImageResource(R.drawable.download_icon_wb_selector);
        mRightSecondIv.setOnClickListener(mOnClickListener);
        mRightFirstIv.setImageResource(R.drawable.history_icon_wb_selector);
        mRightFirstIv.setOnClickListener(mOnClickListener);
        mSearchKeywordTv.setBackgroundResource(R.drawable.rectangle_round_corner_white80);
        mSearchKeywordTv.setOnClickListener(mOnClickListener);
        mActionBar.hide();
    }

    private void initControl() {
        mMain_parent = (RelativeLayout) findViewById(R.id.main_parent);
        mScorePopupWindow = new ScorePopupWindow(NewMainActivity.this,
                mMain_parent);
    }

    /*
     * author qinguoli
     */
    private class RequestAlbumUpdateInfoListTask extends
            MoviesHttpAsyncTask<AlbumUpdateInfoList> {
        @Override
        public void netNull() {
            super.netNull();
            boolean update = checkFavoriteUpdateInNetNull();
            if (myFragment != null)
                ((MyFragment)myFragment).setRedPop(update);
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
            boolean update = checkFavoriteUpdateInNetNull();
            if (myFragment != null)
                ((MyFragment)myFragment).setRedPop(update);
        }

        @Override
        public void dataNull(int updateId, String errMsg) {
            super.dataNull(updateId, errMsg);
            boolean update = checkFavoriteUpdateInNetNull();
            if (myFragment != null)
                ((MyFragment)myFragment).setRedPop(update);
        }

        public RequestAlbumUpdateInfoListTask(Context context) {
            super(context);
        }

        @Override
        public LVideoDataHull<AlbumUpdateInfoList> doInBackground() {
            List<String> aids = new ArrayList<String>();
            String aidString = null;
            for (int i = 0; i < favoriteList.size(); i++) {
                Favorite favorite = favoriteList.get(i);
                String isEnd = favorite.getIsend();
                // 如果影片已经完结则不再请求更新 fix by zhangshuo
                if (!Utils.END.equals(isEnd)) {
                    aids.add(favoriteList.get(i).getAid());
                }
            }
            aidString = TextUtils.join(",", aids);
            return MoviesHttpApi.requestAlbumUpdateInfoList(
                    new AlbumUpdateInfoListParser(aids), aidString);
        }

        @Override
        public void onPostExecute(int updateId, AlbumUpdateInfoList result) {

            albumUpdateInfoList = result;
            List<AlbumUpdateInfoBean> albumUpdateInfoList = result
                    .getAlbumUpdateInfoList();
            update = checkWheatherUpdate(albumUpdateInfoList);
            if (myFragment != null)
                ((MyFragment)myFragment).setRedPop(update);

        }

        /**
         * 无网下判断是否有更新
         *
         * @return
         */
        public boolean checkFavoriteUpdateInNetNull() {
            for (Favorite favor : favoriteList) {
                if (!TextUtils.equals(favor.getLatestEpisodes(),
                        favor.getNowEpisodes())) {
                    return true;
                }
            }
            return false;
        }

        /* 判断是否有更新 */
        public boolean checkWheatherUpdate(
                List<AlbumUpdateInfoBean> albumUpdateInfoList) {

            boolean update = false;
            for (int i = 0; i < albumUpdateInfoList.size(); i++) {
                AlbumUpdateInfoBean albumUpdateInfoBean = albumUpdateInfoList
                        .get(i);
                // 先更新数据库
                if (null != favoriteDao) {
                    favoriteDao.update(albumUpdateInfoBean);
                }
                // 从数据库里查询出最新的信息
                Favorite favorite = favoriteDao.getByAid(albumUpdateInfoBean
                        .getAid());
                String latestEpisodes = favorite.getLatestEpisodes();
                String nowEpisodes = favorite.getNowEpisodes();

                if ((null != latestEpisodes && null != nowEpisodes)
                        && (!latestEpisodes.equals(nowEpisodes))) {

                    update = true;
                    break;
                }

            }

            return update;

        }

    }

    private void updateDownloadIcon() {
        ArrayList<DownloadJob> jobsList = MoviesApplication.getInstance()
                .getDownloadManager().getProvider().getQueuedDownloads();
        if (null != jobsList && jobsList.size() > 0) {
            showDownloadRedpop(true);
            isShowDownloadRed = true;
        } else {
            showDownloadRedpop(false);
            isShowDownloadRed = false;
        }
    }

    private void showDownloadRedpop(final boolean isshow) {
        if(mRedIconView != null){
            if(isshow){
                mRedIconView.setVisibility(View.VISIBLE);
            }else{
                mRedIconView.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                exitBy2Click();
                return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exitBy2Click() {
        LogUtils.e(TAG, "exitBy2Click");
        initExitDialog();
        if(mExitDialog != null){
            mExitDialog.show();
            UmengEventPoster.doEventPost(UmengEventPoster.EXITBOX_SHOW);
            requestQuitAd();
        }
    }

    private void requestQuitAd() {
        new RequestAdTask(MoviesApplication
                .getInstance(), MoviesHttpApi.QUIT, new RequestResultListener<NewAdDataBean>() {

            @Override
            public boolean onRequestFailed() {
                LogUtils.e(TAG, "!!!!!!!!!!!!!!请求广告数据失败!!!!!!!!!!!!!!");
                return false;
            }

            @Override
            public void onRequestSuccess(int updateId, NewAdDataBean result) {
                LogUtils.e(TAG, "!!!!!!!!!!!!!!AdDataBean：" + result);
                if (result != null) {
                    AdRequestStatis.selfResponseReport(result, SelfDataConstant.AD_PO_EXIT);
                    quitAdData = result;
                    LogUtils.e(TAG, "!!!!请求广告数据成功!!!!");
                    initAdExitDialog();
                }
            }

            @Override
            public void onPreRequest() {

            }
        }).start();
    }

    private void initExitDialog() {
        if(mExitView == null){
            LayoutInflater inflater = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            mExitView = inflater.inflate(R.layout.exit_ad_dialog, null);
            mExitDialog = new Dialog(this, R.style.noframe_dialog);
            mExitDialog.setContentView(mExitView);
            Window window = mExitDialog.getWindow() ;
            WindowManager.LayoutParams params = window.getAttributes() ;
            params.width = UIs.dipToPx(281);            //使用这种方式更改了dialog的框宽
            window.setAttributes(params);
            mExitAdRelativeLayout = (RelativeLayout) mExitView.findViewById(R.id.ad_rlayout);
            mExitHeadText = (TextView) mExitView.findViewById(R.id.iv_title);
            mExitImage = (ImageView) mExitView.findViewById(R.id.iv_main);
            mExitTipTv = (TextView) mExitView.findViewById(R.id.ad_tips_tv);
            mExitLogoIv = (ImageView) mExitView.findViewById(R.id.ad_logo_iv);
            resetNoAdExitView();
        }else{
            resetNoAdExitView();
        }
    }
    private void resetNoAdExitView(){
        //无广告
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, UIs.dipToPx(45));
        mExitHeadText.setLayoutParams(params);
        mExitHeadText.setVisibility(View.VISIBLE);
        mExitHeadText.setGravity(Gravity.CENTER);
        mExitHeadText.setText(R.string.app_exit_tips);
        mExitTipTv.setVisibility(View.GONE);
        mExitLogoIv.setVisibility(View.GONE);
        mExitAdRelativeLayout.setVisibility(View.GONE);
        mExitImage.setVisibility(View.GONE);
        mExitView.findViewById(R.id.negative_btn).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap map = new HashMap();
                map.put("hasAd", "no");
                UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_YES, map);
                CDEManager cdeManager = CDEManager.getInstance(MoviesApplication
                        .getInstance());
                cdeManager.stopCde();
                MoviesApplication.getInstance().exitApplication(true);
                mExitDialog.dismiss();
            }
        });
        mExitView.findViewById(R.id.positive_btn).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap map = new HashMap();
                map.put("hasAd", "no");
                UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_NO, map);
                mExitDialog.dismiss();
            }
        });
    }

    private void initAdExitDialog() {
        if (Utils.SERVER_AD.equals(quitAdData.provider)) {
            mExitHeadText.setVisibility(View.GONE);
            mExitImage.setVisibility(View.VISIBLE);
            final ServerPayload serverPayload = (ServerPayload) quitAdData.payload;
            ImageLoader.getInstance().displayImage(serverPayload.pic, mExitImage);
            UmengEventPoster.doPost(UmengEventPoster.SERVERAD_SHOW, "position", "exit");
            mExitImage.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    CommonAdActionHandle.getInstance().doServerAd(NewMainActivity.this, serverPayload, MoviesHttpApi.QUIT);
                    UmengEventPoster.doPost(UmengEventPoster.SERVERAD_CLICK, "position", "exit");
                }
            });
            mExitView.findViewById(R.id.negative_btn).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    HashMap map = new HashMap();
                    map.put("hasAd", "yes");
                    UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_YES, map);
                    CDEManager cdeManager = CDEManager.getInstance(MoviesApplication
                            .getInstance());
                    cdeManager.stopCde();
                    MoviesApplication.getInstance().exitApplication(true);
                    mExitDialog.dismiss();
                }
            });
            mExitView.findViewById(R.id.positive_btn).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    HashMap map = new HashMap();
                    map.put("hasAd", "yes");
                    UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_NO, map);
                    mExitDialog.dismiss();
                }
            });
        } else if (TextUtils.equals(Utils.BAIDU_AD, quitAdData.provider)) {
            AdStatisticsSp.savaOneUp(MoviesApplication.getInstance(), AdStatisticsSp.BAIDUEXITADRESPONSE);
            buildBaiduInterAd(((SDKPayload)quitAdData.payload).adId);
        } else if (TextUtils.equals(Utils.GDT_AD, quitAdData.provider)) {
            buildGdtAd(((SDKPayload)quitAdData.payload).adId, mExitView);
        } else if (TextUtils.equals(Utils.HZ_AD, quitAdData.provider)) {
            buildHzAd((HzPayload)quitAdData.payload, mExitView);
        } else if (TextUtils.equals(Utils.YZ_AD, quitAdData.provider)) {
            buildYzAd((YzPayload)quitAdData.payload, mExitView);
        } else if (TextUtils.equals(Utils.XF_AD, quitAdData.provider)) {
            buildXfAd((XfPayload) quitAdData.payload, mExitView);
        } else if (TextUtils.equals(Utils.TT_AD, quitAdData.provider)) {
            buildAd(quitAdData.payload, mExitView);
        }
    }

    /**
     * 退出广告的构建可以用同一个方法，传不同的payload
     * @param payload
     * @param mExitView
     */
    private void buildAd(Payload payload, View mExitView) {
        mExitHeadText.setVisibility(View.VISIBLE);
        mExitHeadText.setText(R.string.app_exit_tips);
        mExitImage.setVisibility(View.VISIBLE);

        if (payload instanceof TtPayload) {
            TtPayAdView ttPayAdView = new TtPayAdView(NewMainActivity.this, mExitView, "exit");
            ttPayAdView.setTtAd(((TtPayload) payload).ad);
        }
        this.mExitView.findViewById(R.id.negative_btn).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap map = new HashMap();
                map.put("hasAd", "yes");
                UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_YES, map);
                CDEManager cdeManager = CDEManager.getInstance(MoviesApplication
                        .getInstance());
                cdeManager.stopCde();
                MoviesApplication.getInstance().exitApplication(true);
                mExitDialog.dismiss();
            }
        });
        this.mExitView.findViewById(R.id.positive_btn).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap map = new HashMap();
                map.put("hasAd", "yes");
                UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_NO, map);
                mExitDialog.dismiss();
            }
        });
    }

    private void buildYzAd(YzPayload payload, View mExitView) {
        mExitHeadText.setVisibility(View.VISIBLE);
        mExitHeadText.setText(R.string.app_exit_tips);
        mExitImage.setVisibility(View.VISIBLE);
        YzPayAdView yzAdView = new YzPayAdView(NewMainActivity.this, mExitView, "exit");
        yzAdView.setYzAd(payload.ad);
        this.mExitView.findViewById(R.id.negative_btn).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap map = new HashMap();
                map.put("hasAd", "yes");
                UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_YES, map);
                CDEManager cdeManager = CDEManager.getInstance(MoviesApplication
                        .getInstance());
                cdeManager.stopCde();
                MoviesApplication.getInstance().exitApplication(true);
                mExitDialog.dismiss();
            }
        });
        this.mExitView.findViewById(R.id.positive_btn).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap map = new HashMap();
                map.put("hasAd", "yes");
                UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_NO, map);
                mExitDialog.dismiss();
            }
        });
    }

    private void buildHzAd(HzPayload payload, View mExitView) {
        mExitHeadText.setVisibility(View.VISIBLE);
        mExitHeadText.setText(R.string.app_exit_tips);
        mExitImage.setVisibility(View.VISIBLE);
        HzPayAdView hzAdView = new HzPayAdView(NewMainActivity.this, mExitView, "exit");
        hzAdView.setHzAd(payload.ad);
        this.mExitView.findViewById(R.id.negative_btn).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap map = new HashMap();
                map.put("hasAd", "yes");
                UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_YES, map);
                CDEManager cdeManager = CDEManager.getInstance(MoviesApplication
                        .getInstance());
                cdeManager.stopCde();
                MoviesApplication.getInstance().exitApplication(true);
                mExitDialog.dismiss();
            }
        });
        this.mExitView.findViewById(R.id.positive_btn).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap map = new HashMap();
                map.put("hasAd", "yes");
                UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_NO, map);
                mExitDialog.dismiss();
            }
        });
    }

    private void buildXfAd(XfPayload payload, View mExitView) {
        mExitHeadText.setVisibility(View.VISIBLE);
        mExitHeadText.setText(R.string.app_exit_tips);
        mExitImage.setVisibility(View.VISIBLE);
        XfPayAdView xfAdView = new XfPayAdView(NewMainActivity.this, mExitView, "exit");
        xfAdView.setXfAd(payload.ad);
        this.mExitView.findViewById(R.id.negative_btn).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap map = new HashMap();
                map.put("hasAd", "yes");
                UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_YES, map);
                CDEManager cdeManager = CDEManager.getInstance(MoviesApplication
                        .getInstance());
                cdeManager.stopCde();
                MoviesApplication.getInstance().exitApplication(true);
                mExitDialog.dismiss();
            }
        });
        this.mExitView.findViewById(R.id.positive_btn).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap map = new HashMap();
                map.put("hasAd", "yes");
                UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_NO, map);
                mExitDialog.dismiss();
            }
        });
    }


    //生成带广点通广告的退出确认框
    //广点通广告图片长宽3:2
    private void buildGdtAd(String exitAdId, View view) {
        mExitHeadText.setVisibility(View.VISIBLE);
        mExitHeadText.setText(R.string.app_exit_tips);
        mExitImage.setVisibility(View.VISIBLE);
        boolean isHasCache = mExitGdtAdList != null&&mExitGdtAdList.size()>0;
        GdtNativeAdView gdtAd = new GdtNativeAdView(NewMainActivity.this, "exit", view, "exit");
        if(isHasCache && NetWorkTypeUtils.isWifi()){
            Random rand = new Random();
            int i = rand.nextInt(mExitGdtAdList.size());
            gdtAd.showAD(mExitGdtAdList.get(i), "exit");
        }else{
            gdtAd.loadAD(exitAdId);
        }
        this.mExitView.findViewById(R.id.negative_btn).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap map = new HashMap();
                map.put("hasAd", "yes");
                UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_YES, map);
                CDEManager cdeManager = CDEManager.getInstance(MoviesApplication
                        .getInstance());
                cdeManager.stopCde();
                MoviesApplication.getInstance().exitApplication(true);
                mExitDialog.dismiss();
            }
        });
        this.mExitView.findViewById(R.id.positive_btn).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap map = new HashMap();
                map.put("hasAd", "yes");
                UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_NO, map);
                mExitDialog.dismiss();
            }
        });
    }

    //生成带百度插屏广告的退出确认框
    //百度广告图片长宽6:5
    private void buildBaiduInterAd(String exitAdId) {
        mExitHeadText.setVisibility(View.VISIBLE);
        mExitHeadText.setText(R.string.app_exit_tips);
        mExitImage.setVisibility(View.GONE);
        mExitAdRelativeLayout.setVisibility(View.VISIBLE);
        createBaiduInterAd(exitAdId);
        mExitView.findViewById(R.id.negative_btn).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap map = new HashMap();
                map.put("hasAd", "yes");
                UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_YES, map);
                CDEManager cdeManager = CDEManager.getInstance(MoviesApplication
                        .getInstance());
                cdeManager.stopCde();
                MoviesApplication.getInstance().exitApplication(true);
                mExitDialog.dismiss();
            }
        });
        mExitView.findViewById(R.id.positive_btn).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                HashMap map = new HashMap();
                map.put("hasAd", "yes");
                UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_NO, map);
                mExitDialog.dismiss();
            }
        });
    }

    private void createBaiduInterAd(String id) {
        baiduInterExitAdView = new BaiduInterAdView(this, mExitAdRelativeLayout, "exit");
        baiduInterExitAdView.setAdListener(new MyOnAdListener() {
            @Override
            public void onAdDismissed() {
                if (mExitDialog != null) {
                    HashMap map = new HashMap();
                    map.put("hasAd", "yes");
                    UmengEventPoster.doPost(UmengEventPoster.EXIT_DIALOG_NO, map);
                    mExitDialog.dismiss();
                }
            }

            @Override
            public void onAdFailed() {

            }

            @Override
            public void onAdPresent() {

            }

            @Override
            public void onAdSuccess(Object obj) {

            }
        });
        baiduInterExitAdView.setExitBaiduAd(id);
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        unregisterCheckNetwork();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        pHuaweiPushInterface.onStop(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UpdateSnifferManager.getInstance().resetVariable();
        com.baidu.mobads.production.BaiduXAdSDKContext.exit();
        mLocationManager.stopLocation();
        MoviesApplication.isSaveLogContinue = false;
        LogCat.e(TAG, "onDestroy");
        if(mReportTimer != null){
            mReportTimer.cancel();
        }
        if(mExitGdtAdTimer != null){
            mExitGdtAdTimer.cancel();
        }
        MoviesConstant.isIn4GPlayVideo = false;
        MoviesConstant.isFirstIn4GPlayVideo = true;
    }

    private void handleBottomSelect() {
        bottomIndex = getIntent().getStringExtra(PushUtil.EXTRA_PUSH_NOTIFICATION);
        if (PushUtil.TAB_INDEX_HOME.equals(bottomIndex)) {
            setBottomSelete(1);
        } else if (PushUtil.TAB_INDEX_TOPIC.equals(bottomIndex)) {
            setBottomSelete(3);
        } else if (PushUtil.TAB_INDEX_ONEPOINT.equals(bottomIndex)) {
            if (tabHotLl != null && tabHotLl.getVisibility() == View.VISIBLE) {
                setBottomSelete(6);
            }
        }
        getIntent().putExtra(PushUtil.EXTRA_PUSH_NOTIFICATION, "");
    }

    @Override
    protected void onResume() {
        super.onResume();
        setCurrentPage();
        LogCat.e(TAG, "onResume");
        MoviesApplication.getInstance().setLastPageClassName(getFragmentString(mCurrentTabPosition));
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                handleBottomSelect();
            }
        }, 300);
        if (MoviesHttpApi.TEST) {
            UIs.showToast(R.string.tip_use_test);
        }
        Long resumeTime = System.currentTimeMillis();
        favoriteDao = new FavoriteDao(this);
        favoriteList = favoriteDao.getAll();

        if (0 != favoriteList.size()) {
            requstAlbumUpdateInfoListTask = new RequestAlbumUpdateInfoListTask(
                    this);
            requstAlbumUpdateInfoListTask.start();
        } else {
            if (myFragment != null)
                ((MyFragment)myFragment).setRedPop(false);
        }

        mPlayRecordDao = new PlayRecordDao(this);
        mPlayRecordList = mPlayRecordDao.getAll();

        if(MoviesApplication.isLoginDone){
            if(!favoriteList.isEmpty() || (mPlayRecordList != null && mPlayRecordList.size() > 0)) {//判断本地收藏或者播放记录不为空则弹出合并提示
                mLocalDataSyncDialg.show();
            }else{

            }
            new RequestUserPlayRecordsTask(this, 0, 200).start();
            MoviesApplication.isLoginDone = false;
        }

        updateDownloadIcon();
        LogUtils.userTime("onResume", resumeTime);
        MobclickAgent.onResume(this);
        registerCheckNetwork();
    }

    /**
     * qinguoli 注册监听手机网络广播 接收
     */
    protected void registerCheckNetwork() {
        mCheckReceiver = new NetworkCheckReceiver();
        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction(PlayerUtils.CONNECTIVTY_CHANGE);
        intentfilter.addAction(Utils.SDCARD_NOSPACE_ACTION);
        this.registerReceiver(mCheckReceiver, intentfilter);
    }

    /**
     * qinguoli 取消对网络变化的监听*
     */
    protected void unregisterCheckNetwork() {
        if (mCheckReceiver != null) {
            try {
                this.unregisterReceiver(mCheckReceiver);
            } catch (IllegalArgumentException e) {
                if (e.getMessage().contains("Receiver not registered")) {
                    LogUtils.e(TAG, "!!!!!!!!!!!!!!!!!ignore incorrect unregisterCheckNetwork!!!!!!!!!!!!!!!!!");
                    // Ignore this exception. This is exactly what is desired
                } else {
                    // unexpected, re-throw
                    throw e;
                }
            }
        }
    }

    /**
     * qinguoli 网络广播监听*
     */
    class NetworkCheckReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                if (intent.getAction().equals(PlayerUtils.CONNECTIVTY_CHANGE)) {
                    // 读取保存的之前网络状态
                    SharedPreferences priorNetState = getSharedPreferences(
                            "priornetstate", Activity.MODE_PRIVATE);
                    int priorNetType = priorNetState.getInt("netstate", 2);
                    int nowNetType = NetWorkTypeUtils.checkNet(intent,
                            priorNetType);
                    Editor editor = priorNetState.edit();
                    editor.putInt("netstate", nowNetType);
                    editor.commit();
                }
                if (intent.getAction().equals(Utils.SDCARD_NOSPACE_ACTION)) {
                    DialogUtil.getInstance(NewMainActivity.this)
                            .checkSDCardSpaceDialog();
                }
            }
        }
    }

    private void startPushBroadcastReceiver() {
        Intent intent = new Intent();
        intent.setAction(PushBroadcastReceiver.START_PUSH_ACTION);
        sendBroadcast(intent);

    }

    private class MyupdateListener implements UpdateListener {

        @Override
        public void onCancel() {
            // TODO Auto-generated method stub
        }

        @Override
        public void onFinish() {
            MoviesApplication.getInstance().exitApplication(false);
        }

        @Override
        public void onCheckError() {
            // TODO Auto-generated method stub
        }

        @Override
        public void onComplete() {
            // TODO Auto-generated method stub
            // mHandler.sendEmptyMessageDelayed(JUMP, 3000);
        }

    }

    /**
     * 判断包名和versionCode，是否是正版
     */
    private void isOriginal() {
        String pkName = this.getPackageName();
        int versionCode = 0;
        try {
            versionCode = this.getPackageManager().getPackageInfo(pkName, 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        mUpdateManager = new UpdateManager(this);
        if (!StringUtil.isEmpty(MoviesConstant.PKNAME)
                && MoviesConstant.PKNAME.equals(pkName)
                && MoviesConstant.VERSIONCODE == versionCode) {
            // 升级--在检测包名和vesioncode之后
            mUpdateManager.setmUpdateListener(new MyupdateListener());
            mUpdateManager.startCheck();
        } else {
            // 强制升级
            mUpdateManager.showOriginalDialog();
        }
    }

    private class MyOnClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.right_second_iv:
                    Intent intent = new Intent(NewMainActivity.this,
                            DownloadActivity.class);
                    startActivity(intent);
                    break;
                case R.id.right_first_iv:
                    if(mCurrentTabPosition == 0){
                        PlayHistoryActivity.launch(NewMainActivity.this);
                    }else{
                        SearchActivity.launch(NewMainActivity.this);
                    }
                    break;
                case R.id.search_keyword:
                    SearchActivity.launch(NewMainActivity.this);
                    break;
                case R.id.tab_home_ll:
                    setBottomSelete(1);
                    break;
                case R.id.tab_channel_ll:
                    setBottomSelete(2);
                    break;
                case R.id.tab_topic_ll:
                    setBottomSelete(3);
                    break;
                case R.id.tab_rank_ll:
                    setBottomSelete(4);
                    break;
                case R.id.tab_my_ll:
                    setBottomSelete(5);
//                    CommonAdActionHandle.getInstance().downloadApp(NewMainActivity.this, "tecent", CommonAdActionHandle.testDownloadUrl);
                    break;
                case R.id.tab_hot_ll:
                    setBottomSelete(6);
                    break;
                case R.id.yidian_guide_desc:
                case R.id.yidian_guide_hot:
                    yidianGuide.setVisibility(View.GONE);
                    SharePreferenceManager.saveVaule(NewMainActivity.this, SharePreferenceManager.YIDIAN_OPEN_NUM,YIDIAN_OPEN_NUM_10+1);
                    setBottomSelete(6);
                    // 埋点
                    YiDianGuideDataRecord dataRecordEnter = new YiDianGuideDataRecord();
                    dataRecordEnter.setCur_url("instruct");
                    dataRecordEnter.setAcode("0");
                    dataRecordEnter.setAp("enter");
                    if (openNum == YIDIAN_OPEN_NUM_2) {
                        dataRecordEnter.setFre(1);
                    } else if (openNum == YIDIAN_OPEN_NUM_10) {
                        dataRecordEnter.setFre(2);
                    }
                    RealmDaoManager.addMyDataRecord(dataRecordEnter);
                    break;
                case R.id.ly_yidian_guide:
                    yidianGuide.setVisibility(View.GONE);
                    // 埋点
                    YiDianGuideDataRecord dataRecordSkip = new YiDianGuideDataRecord();
                    dataRecordSkip.setCur_url("instruct");
                    dataRecordSkip.setAcode("0");
                    dataRecordSkip.setAp("skip");
                    if (openNum == YIDIAN_OPEN_NUM_2) {
                        dataRecordSkip.setFre(1);
                    } else if (openNum == YIDIAN_OPEN_NUM_10) {
                        dataRecordSkip.setFre(2);
                    }
                    RealmDaoManager.addMyDataRecord(dataRecordSkip);
                    break;
                default:
                    break;
            }
        }
    }


    public void setBottomSelete(int i) {
        // 高亮显示底部导航栏对应的模块
        FragmentTransaction transaction = fManager.beginTransaction();
        hideFragments(transaction);
        mCurrentTabPosition = i-1;
        switch (i) {
            case 1:
                tabHomeLl.setSelected(true);
                tabHotLl.setSelected(false);
                tabChannelLl.setSelected(false);
                tabTopicLl.setSelected(false);
                tabRankLl.setSelected(false);
                tabMyLl.setSelected(false);
                if (homeFragment == null) {
                    // 如果fg1为空，则创建一个并添加到界面上
                    homeFragment = new NewHomeFragment();
                    transaction.add(R.id.main_content, homeFragment);
                    homeFragment.setArguments(mBundle);
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(homeFragment);
                }
                try {
                    transaction.commitAllowingStateLoss();
                } catch (Exception e) {

                }
                mSearchKeywordTv.setVisibility(View.GONE);
//                if(isSecondStatus){
//                    isShowWhiteBg = true;
//                    if(isShowDownloadRed){
//                        mRedIconView.setVisibility(View.VISIBLE);
//                    }else{
//                        mRedIconView.setVisibility(View.GONE);
//                    }
//                    mRightSecondIv.setImageResource(R.drawable.download_icon_bb_selector);
//                    mRightFirstIv.setImageResource(R.drawable.history_icon_bb_selector);
//                    mActionView.setBackgroundResource(R.drawable.rectangle_with_bottom_border);
//                }else{
//                    isShowWhiteBg = false;
//                    if(isShowDownloadRed){
//                        mRedIconView.setVisibility(View.VISIBLE);
//                    }else{
//                        mRedIconView.setVisibility(View.GONE);
//                    }
//                    mRightSecondIv.setImageResource(R.drawable.download_icon_wb_selector);
//                    mRightFirstIv.setImageResource(R.drawable.history_icon_wb_selector);
//                    mActionView.setBackgroundResource(R.drawable.home_title_bg_shape);
//                }
//                mActionView.getBackground().setAlpha(titleAlpha);
                mActionBar.hide();
                mTitleTv.setText("");
                mTitleTv.setVisibility(View.VISIBLE);
                mUtilsTabs.setVisibility(View.GONE);
                mCurrentBottomTab = "home";
                currentPageId = homeFragment.getCurrentPageIndex();
                setCurrentClassName(HomeTestFragment.TAG);
                if (mTabDataRecord != null) {
                    mTabDataRecord.setCur_url("home");
                    mTabDataRecord.setAcode("41");
                    mTabDataRecord.setCtime(System.currentTimeMillis() + "");
                    RealmDaoManager.addMyDataRecord(mTabDataRecord);
                }
            break;
            case 2:
                tabHomeLl.setSelected(false);
                tabHotLl.setSelected(false);
                tabChannelLl.setSelected(true);
                tabTopicLl.setSelected(false);
                tabRankLl.setSelected(false);
                tabMyLl.setSelected(false);
                if (utilsFragment == null) {
                    // 如果fg1为空，则创建一个并添加到界面上
                    utilsFragment = UtilsFragment.newInstance(2);
                    Bundle bundle=new Bundle();
                    utilsFragment.setArguments(bundle);
                    transaction.add(R.id.main_content, utilsFragment);
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(utilsFragment);
                }
//                ((UtilsFragment)utilsFragment).setTabs(mUtilsTabs);
                transaction.commitAllowingStateLoss();
                mSearchKeywordTv.setVisibility(View.GONE);
                isShowWhiteBg = true;
                if(isShowDownloadRed){
                    mRedIconView.setVisibility(View.VISIBLE);
                }else{
                    mRedIconView.setVisibility(View.GONE);
                }
                mRightSecondIv.setImageResource(R.drawable.download_icon_bb_selector);
                mRightFirstIv.setImageResource(R.drawable.search_icon_bb_selector);
                mRightFirstIv.setVisibility(View.GONE);
                mRightSecondIv.setVisibility(View.GONE);
                mActionView.setBackgroundResource(R.drawable.rectangle_with_bottom_border);
                mActionView.getBackground().setAlpha(255);
                mActionBar.show();
                mTitleTv.setText(R.string.bottom_tab_channel_tv);
                mTitleTv.setVisibility(View.GONE);
                mUtilsTabs.setVisibility(View.GONE);
                mSearchKeywordTv.setVisibility(View.VISIBLE);
                RelativeLayout search = (RelativeLayout) (mSearchKeywordTv.findViewById(R.id.search_keyword_rl));
                search.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
                TextView searchText = (TextView) (mSearchKeywordTv.findViewById(R.id.search_keyword_tv));
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) searchText.getLayoutParams();
                params.setMargins(getResources().getDimensionPixelSize(R.dimen.font_12),
                        0, 0 , 0);
                searchText.setLayoutParams(params);
                mCurrentBottomTab = BigDataConstants.PGV_CURRENT_ID_CATEGORY;
                currentPageId = BigDataConstants.PGV_CURRENT_ID_CATEGORY;
                BigDataApi.bigDataPageShowReport(BigDataConstants.PGV_CURRENT_ID_CATEGORY, new HashMap<String, String>(), this);
                setCurrentClassName(ChannelFragment.TAG);
                if (mTabDataRecord != null) {
                    mTabDataRecord.setCur_url("VideoClips");
                    mTabDataRecord.setAcode("0");
                    mTabDataRecord.setCtime(System.currentTimeMillis() + "");
                    RealmDaoManager.addMyDataRecord(mTabDataRecord);
                }
                break;
            case 3:
                tabHomeLl.setSelected(false);
                tabHotLl.setSelected(false);
                tabChannelLl.setSelected(false);
                tabTopicLl.setSelected(true);
                tabRankLl.setSelected(false);
                tabMyLl.setSelected(false);
                if (topicFragment == null) {
                    // 如果fg1为空，则创建一个并添加到界面上
                    topicFragment = TopicFragment.newInstance(3);
                    transaction.add(R.id.main_content, topicFragment);
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(topicFragment);
                }
                transaction.commitAllowingStateLoss();
                mSearchKeywordTv.setVisibility(View.GONE);
                isShowWhiteBg = true;
                if(isShowDownloadRed){
                    mRedIconView.setVisibility(View.VISIBLE);
                }else{
                    mRedIconView.setVisibility(View.GONE);
                }
                mRightSecondIv.setImageResource(R.drawable.download_icon_bb_selector);
                mRightFirstIv.setImageResource(R.drawable.search_icon_bb_selector);
                mRightFirstIv.setVisibility(View.VISIBLE);
                mRightSecondIv.setVisibility(View.VISIBLE);
                mActionView.setBackgroundResource(R.drawable.rectangle_with_bottom_border);
                mActionView.getBackground().setAlpha(255);
                mActionBar.show();
                mTitleTv.setText(R.string.bottom_tab_topic_tv);
                mTitleTv.setVisibility(View.VISIBLE);
                mUtilsTabs.setVisibility(View.GONE);
                mCurrentBottomTab = BigDataConstants.PGV_CURRENT_ID_TOPIC;
                currentPageId = BigDataConstants.PGV_CURRENT_ID_TOPIC;
                BigDataApi.bigDataPageShowReport(BigDataConstants.PGV_CURRENT_ID_TOPIC, new HashMap(), this);
                setCurrentClassName(TopicFragment.TAG);
                if (mTabDataRecord != null) {
                    mTabDataRecord.setCur_url("topic");
                    mTabDataRecord.setAcode("41");
                    mTabDataRecord.setCtime(System.currentTimeMillis() + "");
                    RealmDaoManager.addMyDataRecord(mTabDataRecord);
                }
                break;
            case 4:
                tabHomeLl.setSelected(false);
                tabHotLl.setSelected(false);
                tabChannelLl.setSelected(false);
                tabTopicLl.setSelected(false);
                tabRankLl.setSelected(true);
                tabMyLl.setSelected(false);
                if (rankFragment == null) {
                    // 如果fg1为空，则创建一个并添加到界面上
                    rankFragment = RankFragment.newInstance(4);
                    transaction.add(R.id.main_content, rankFragment);
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(rankFragment);
                }
                transaction.commitAllowingStateLoss();
                mSearchKeywordTv.setVisibility(View.GONE);
                isShowWhiteBg = true;
                if(isShowDownloadRed){
                    mRedIconView.setVisibility(View.VISIBLE);
                }else{
                    mRedIconView.setVisibility(View.GONE);
                }
                mRightSecondIv.setImageResource(R.drawable.download_icon_bb_selector);
                mRightFirstIv.setImageResource(R.drawable.search_icon_bb_selector);
                mRightFirstIv.setVisibility(View.VISIBLE);
                mRightSecondIv.setVisibility(View.VISIBLE);
                mActionView.setBackgroundResource(R.drawable.rectangle_with_bottom_border);
                mActionView.getBackground().setAlpha(255);
                mActionBar.show();
                mTitleTv.setText(R.string.bottom_tab_rank_tv);
                mTitleTv.setVisibility(View.VISIBLE);
                mUtilsTabs.setVisibility(View.GONE);
                mCurrentBottomTab = BigDataConstants.PGV_CURRENT_ID_RANKING;
                currentPageId = BigDataConstants.PGV_CURRENT_ID_RANKING;
                BigDataApi.bigDataPageShowReport(BigDataConstants.PGV_CURRENT_ID_RANKING, new HashMap<String, String>(), this);
                setCurrentClassName(RankFragment.TAG);
                if (mTabDataRecord != null) {
                    mTabDataRecord.setCur_url("ranking");
                    mTabDataRecord.setAcode("41");
                    mTabDataRecord.setCtime(System.currentTimeMillis() + "");
                    RealmDaoManager.addMyDataRecord(mTabDataRecord);
                }
                break;
            case 5:
                tabHomeLl.setSelected(false);
                tabHotLl.setSelected(false);
                tabChannelLl.setSelected(false);
                tabTopicLl.setSelected(false);
                tabRankLl.setSelected(false);
                tabMyLl.setSelected(true);
                if (myFragment == null) {
                    // 如果fg1为空，则创建一个并添加到界面上
                    myFragment = new MyFragment();
                    transaction.add(R.id.main_content, myFragment);
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(myFragment);
                }
                transaction.commitAllowingStateLoss();
                if (myFragment != null)
                    ((MyFragment)myFragment).setRedPop(update);
                mSearchKeywordTv.setVisibility(View.GONE);
                isShowWhiteBg = true;
                if(isShowDownloadRed){
                    mRedIconView.setVisibility(View.VISIBLE);
                }else{
                    mRedIconView.setVisibility(View.GONE);
                }
                mRightSecondIv.setImageResource(R.drawable.download_icon_bb_selector);
                mRightFirstIv.setImageResource(R.drawable.search_icon_bb_selector);
                mRightFirstIv.setVisibility(View.VISIBLE);
                mRightSecondIv.setVisibility(View.VISIBLE);
                mActionView.setBackgroundResource(R.drawable.rectangle_with_bottom_border);
                mActionView.getBackground().setAlpha(255);
                mActionBar.show();
                mTitleTv.setText(R.string.bottom_tab_my_tv);
                mTitleTv.setVisibility(View.VISIBLE);
                mUtilsTabs.setVisibility(View.GONE);
                mCurrentBottomTab = "my";
                currentPageId = "my";
                BigDataApi.bigDataPageShowReport("my", new HashMap<String, String>(), this);
                setCurrentClassName(MyFragment.TAG);
                if (mTabDataRecord != null) {
                    mTabDataRecord.setCur_url("my");
                    mTabDataRecord.setAcode("41");
                    mTabDataRecord.setCtime(System.currentTimeMillis() + "");
                    RealmDaoManager.addMyDataRecord(mTabDataRecord);
                }
                break;
            case 6:
                tabHomeLl.setSelected(false);
                tabHotLl.setSelected(true);
                tabChannelLl.setSelected(false);
                tabTopicLl.setSelected(false);
                tabRankLl.setSelected(false);
                tabMyLl.setSelected(false);
                if (hotFragment == null) {
                    // 如果fg1为空，则创建一个并添加到界面上
                    if (PushUtil.TAB_INDEX_ONEPOINT.equals(bottomIndex)){
                        //从push跳转过来
                        hotFragment = OnePointFragment.newInstance(3);
                    }else{
                        hotFragment = OnePointFragment.newInstance(2);
                    }

                    transaction.add(R.id.main_content, hotFragment);
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(hotFragment);
                }
                transaction.commitAllowingStateLoss();
                mSearchKeywordTv.setVisibility(View.GONE);
                isShowWhiteBg = true;
                mRedIconView.setVisibility(View.GONE);
                mRightFirstIv.setVisibility(View.GONE);
                mRightSecondIv.setVisibility(View.GONE);
                mActionView.setBackgroundResource(R.drawable.rectangle_with_bottom_border);
                mActionView.getBackground().setAlpha(255);
                mActionBar.show();
                mTitleTv.setText("热门视频");
                mTitleTv.setVisibility(View.VISIBLE);
                mCurrentBottomTab = BigDataConstants.PGV_CURRENT_ID_HOT;
                currentPageId = BigDataConstants.PGV_CURRENT_ID_HOT;
                BigDataApi.bigDataPageShowReport(BigDataConstants.PGV_CURRENT_ID_HOT, new HashMap(), this);
                setCurrentClassName(OnePointFragment.TAG);
                //一点资讯上报
                reportClick();
                if (mTabDataRecord != null) {
                    mTabDataRecord.setCur_url("VideoClips");
                    mTabDataRecord.setAcode("0");
                    mTabDataRecord.setCtime(System.currentTimeMillis() + "");
                    RealmDaoManager.addMyDataRecord(mTabDataRecord);
                }
                break;
            default:
                transaction.commitAllowingStateLoss();
                break;
        }
    }

    private void reportClick() {
        UmengEventPoster.doEventPost(BigDataConstants.CLICKVIDEOCLIPS);
    }

    private void hideFragments(FragmentTransaction transaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }
        if (utilsFragment != null) {
            transaction.hide(utilsFragment);
        }
        if (topicFragment != null) {
            transaction.hide(topicFragment);
        }
        if (rankFragment != null) {
            transaction.hide(rankFragment);
        }
        if (myFragment != null) {
            transaction.hide(myFragment);
        }
        if(hotFragment != null ){
            transaction.hide(hotFragment);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //JPush中调 HMS SDK解决错误的接 传 的requestCode为10001, 开发者调 是请注意 要同样使 10001
        if(requestCode == JPluginPlatformInterface.JPLUGIN_REQUEST_CODE) {
            pHuaweiPushInterface.onActivityResult(this, requestCode, resultCode, data);
        }
    }

    public class RequestAddAllFavoriteTask extends MoviesHttpAsyncTask<CommonBean> {

        private List<UploadCollectionBean> list;

        @Override
        public void netNull() {
            super.netNull();
        }

        @Override
        public void netErr(int updateId, String errMsg) {
            super.netErr(updateId, errMsg);
        }

        @Override
        public void dataNull(int updateId, String errMsg) {
            super.dataNull(updateId, errMsg);
            ToastUtil.showShortToast(NewMainActivity.this, getResources().getString(R.string.sync_fail));
        }

        public RequestAddAllFavoriteTask(Context context, List<UploadCollectionBean> list) {
            super(context);
            this.list = list;
        }

        @Override
        public LVideoDataHull<CommonBean> doInBackground() {
            LVideoDataHull<CommonBean> ret = MoviesHttpApi.addAllfavoriteRequest(
                    new CommonParser(), list);
            return ret;
        }

        @Override
        public void onPostExecute(int updateId, CommonBean result) {
            if (result != null && "200".equals(result.getCode())) {
                //合并成功,删除本地数据库数据
                ToastUtil.showShortToast(NewMainActivity.this, getResources().getString(R.string.sync_success));
                for(int i = 0; i < favoriteList.size(); i++) {
                    favoriteDao.delete(favoriteList.get(i).getAid());
                }
                if(uploadCollectionList != null) {
                    uploadCollectionList.clear();
                }
            }else {
                ToastUtil.showShortToast(NewMainActivity.this, getResources().getString(R.string.sync_fail));
            }
        }
    }

    @Override
    public void showFirstStatus() {
//        isSecondStatus = false;
//        isShowWhiteBg = false;
//        if(isShowDownloadRed){
//            mRedIconView.setVisibility(View.VISIBLE);
//        }else{
//            mRedIconView.setVisibility(View.GONE);
//        }
//        mRightSecondIv.setImageResource(R.drawable.download_icon_wb_selector);
//        mRightFirstIv.setImageResource(R.drawable.history_icon_wb_selector);
//        mSearchKeywordTv.setBackgroundResource(R.drawable.rectangle_round_corner_white80);
//        mActionView.setBackgroundResource(R.drawable.home_title_bg_shape);
    }

    @Override
    public void showSecondStatus() {
//        isSecondStatus = true;
//        isShowWhiteBg = true;
//        if(isShowDownloadRed){
//            mRedIconView.setVisibility(View.VISIBLE);
//        }else{
//            mRedIconView.setVisibility(View.GONE);
//        }
//        mRightSecondIv.setImageResource(R.drawable.download_icon_bb_selector);
//        mRightFirstIv.setImageResource(R.drawable.history_icon_bb_selector);
//        mSearchKeywordTv.setBackgroundResource(R.drawable.rectangle_round_corner_f5);
//        mActionView.setBackgroundResource(R.drawable.rectangle_with_bottom_border);
    }

    @Override
    public void showGradientChange(int alpha){
//        if(alpha < 256 && alpha >= 0){
//            titleAlpha = alpha;
//            mActionView.getBackground().setAlpha(alpha);
//        }else{
//            mActionView.getBackground().setAlpha(255);
//        }
    }

    public String getmCurrentBottomTab() {
        return mCurrentBottomTab;
    }

    public void setmCurrentBottomTab(String mCurrentBottomTab) {
        this.mCurrentBottomTab = mCurrentBottomTab;
    }

    public String getFragmentString(int i) {
        switch(i) {
            case 0:
                return "RecommendFragment";
            case 1:
                return "ChannelFragment";
            case 2:
                return "TopicFragment";
            case 3:
                return "RankFragment";
            case 4:
                return "MyFragment";
            case 5:
                return  "OnePointFragment";
        }
        return "unknow";

    }

    @Override
    public void dealWithUmeng() {
        LogUtils.i(TAG, "currentTabPosition is " + mCurrentTabPosition);
        switch (mCurrentTabPosition) {
            case 0 :
                UmengEventPoster.postPageLeaveTime(UmengEventPoster.LEAVE_RECOMMEND);
                break;
            case 1 :
                UmengEventPoster.postPageLeaveTime(UmengEventPoster.LEAVE_CHANNEL);
                break;
            case 2 :
                UmengEventPoster.postPageLeaveTime(UmengEventPoster.LEAVE_TOPIC_LIST);
                break;
            case 3 :
                UmengEventPoster.postPageLeaveTime(UmengEventPoster.LEAVE_RANK);
                break;
            case 4:
                UmengEventPoster.postPageLeaveTime(UmengEventPoster.LEAVE_MY);
                break;
            case 5:
                UmengEventPoster.postPageLeaveTime(UmengEventPoster.LEAVE_HOT);
                break;
        }

    }

    @Override
    public void dealWithVisitUmeng() {

    }

    private void setCurrentPage(){
        switch (mCurrentTabPosition) {
            case 0 :
                mCurrentBottomTab = "home";
                if(homeFragment != null){
                    currentPageId = homeFragment.getCurrentPageIndex();
                }else{
                    currentPageId = BigDataConstants.PGV_CURRENT_ID_HOME;
                }
                break;
            case 1 :
                mCurrentBottomTab = BigDataConstants.PGV_CURRENT_ID_CATEGORY;
                currentPageId = BigDataConstants.PGV_CURRENT_ID_CATEGORY;
                break;
            case 2 :
                mCurrentBottomTab = BigDataConstants.PGV_CURRENT_ID_TOPIC;
                currentPageId = BigDataConstants.PGV_CURRENT_ID_TOPIC;
                break;
            case 3 :
                mCurrentBottomTab = BigDataConstants.PGV_CURRENT_ID_RANKING;
                currentPageId = BigDataConstants.PGV_CURRENT_ID_RANKING;
                break;
            case 4:
                mCurrentBottomTab = "my";
                currentPageId = "my";
                break;
            case 5 :
                mCurrentBottomTab = BigDataConstants.PGV_CURRENT_ID_HOT;
                currentPageId = BigDataConstants.PGV_CURRENT_ID_HOT;
                break;
            default:
                mCurrentBottomTab = "home";
                currentPageId = BigDataConstants.PGV_CURRENT_ID_HOME;
                break;
        }
    }
}